using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Repositories;

namespace Lzfy_Refund_Service.Services
{
    public class VerifyInfoService : IVerifyInfoService
    {
        private readonly IVerifyInfoRepository _verifyInfoRepository;

        public VerifyInfoService(IVerifyInfoRepository verifyInfoRepository)
        {
            _verifyInfoRepository = verifyInfoRepository;
        }

        public async Task<VerifyInfo?> GetByIdAsync(int id)
        {
            return await _verifyInfoRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<VerifyInfo>> GetAllAsync()
        {
            return await _verifyInfoRepository.GetAllAsync();
        }

        public async Task<IEnumerable<VerifyInfo>> GetByPatientIdAsync(string patientId)
        {
            if (string.IsNullOrEmpty(patientId))
                throw new ArgumentException("Patient ID cannot be null or empty", nameof(patientId));

            return await _verifyInfoRepository.GetByPatientIdAsync(patientId);
        }

        public async Task<VerifyInfo?> GetByVerifyCodeAsync(string verifyCode)
        {
            if (string.IsNullOrEmpty(verifyCode))
                throw new ArgumentException("Verify code cannot be null or empty", nameof(verifyCode));

            return await _verifyInfoRepository.GetByVerifyCodeAsync(verifyCode);
        }

        public async Task<VerifyInfo?> GetByQrCodeAsync(string qrCode)
        {
            if (string.IsNullOrEmpty(qrCode))
                throw new ArgumentException("QR code cannot be null or empty", nameof(qrCode));

            return await _verifyInfoRepository.GetByQrCodeAsync(qrCode);
        }

        public async Task<IEnumerable<VerifyInfo>> GetRecentAsync(int minutes, string? userId = null)
        {
            if (minutes <= 0)
                throw new ArgumentException("Minutes must be greater than 0", nameof(minutes));

            return await _verifyInfoRepository.GetRecentAsync(minutes, userId);
        }

        public async Task<VerifyInfoQueryResponse> GetWithFilterAsync(VerifyInfoQueryRequest request)
        {
            if (request == null)
                throw new ArgumentNullException(nameof(request));

            if (request.PageIndex < 1)
                request.PageIndex = 1;

            if (request.PageSize < 1 || request.PageSize > 100)
                request.PageSize = 20;

            var (data, totalCount) = await _verifyInfoRepository.GetWithFilterAsync(
                request.PatientId,
                request.VerifyCode,
                null, // userId parameter
                request.PatName,
                request.IdNumber,
                request.StartDate,
                request.EndDate,
                request.PageIndex,
                request.PageSize);

            return new VerifyInfoQueryResponse
            {
                Items = data.ToList(),
                TotalCount = totalCount,
                PageIndex = request.PageIndex,
                PageSize = request.PageSize
            };
        }

        public async Task<int> CreateAsync(VerifyInfoCreateRequest request)
        {
            if (request == null)
                throw new ArgumentNullException(nameof(request));

            // 验证必填字段
            if (string.IsNullOrEmpty(request.PatientId))
                throw new ArgumentException("Patient ID is required", nameof(request.PatientId));

            // 允许相同的验证码插入，已移除唯一性检查

            // 允许相同的二维码插入，已移除唯一性检查

            var verifyInfo = new VerifyInfo
            {
                InputDate = DateTime.Now,
                PatientId = request.PatientId,
                VerifyCode = request.VerifyCode,
                QrCode = request.QrCode,
                RefundBalance = request.RefundBalance,
                UserId = request.UserId,
                UserName = request.UserName,
                PatName = request.PatName,
                IdNumber = request.IdNumber,
                Deleted = false, // 新创建的记录默认未删除
                DeletedTime = null, // 新创建的记录删除时间为空
                DeletedBy = null // 新创建的记录删除者为空
            };

            return await _verifyInfoRepository.CreateAsync(verifyInfo);
        }

        public async Task<bool> UpdateAsync(int id, VerifyInfoUpdateRequest request)
        {
            if (request == null)
                throw new ArgumentNullException(nameof(request));

            var existingVerifyInfo = await _verifyInfoRepository.GetByIdAsync(id);
            if (existingVerifyInfo == null)
                throw new InvalidOperationException($"Verify info with ID {id} not found");

            // 允许相同的验证码和二维码更新，已移除唯一性检查

            // 更新字段
            existingVerifyInfo.PatientId = request.PatientId ?? existingVerifyInfo.PatientId;
            existingVerifyInfo.VerifyCode = request.VerifyCode ?? existingVerifyInfo.VerifyCode;
            existingVerifyInfo.QrCode = request.QrCode ?? existingVerifyInfo.QrCode;
            existingVerifyInfo.RefundBalance = request.RefundBalance ?? existingVerifyInfo.RefundBalance;
            existingVerifyInfo.UserId = request.UserId ?? existingVerifyInfo.UserId;
            existingVerifyInfo.UserName = request.UserName ?? existingVerifyInfo.UserName;
            existingVerifyInfo.PatName = request.PatName ?? existingVerifyInfo.PatName;
            existingVerifyInfo.IdNumber = request.IdNumber ?? existingVerifyInfo.IdNumber;

            return await _verifyInfoRepository.UpdateAsync(existingVerifyInfo);
        }

        public async Task<bool> DeleteAsync(int id)
        {
            if (id <= 0)
                throw new ArgumentException("ID must be greater than 0", nameof(id));

            var existingVerifyInfo = await _verifyInfoRepository.GetByIdAsync(id);
            if (existingVerifyInfo == null)
                return false;

            return await _verifyInfoRepository.DeleteAsync(id);
        }
        
        public async Task<bool> SoftDeleteAsync(int id, string deletedBy)
        {
            if (id <= 0)
                throw new ArgumentException("ID must be greater than 0", nameof(id));
            
            if (string.IsNullOrWhiteSpace(deletedBy))
                throw new ArgumentException("DeletedBy cannot be null or empty", nameof(deletedBy));

            var existingVerifyInfo = await _verifyInfoRepository.GetByIdAsync(id);
            if (existingVerifyInfo == null)
                return false;

            return await _verifyInfoRepository.SoftDeleteAsync(id, deletedBy);
        }
    }
}